﻿using System;
using System.Windows.Controls;
using System.Windows;
using System.Reflection;
using System.Windows.Media;

namespace Inspire.Utility
{
    static class DataGridHelper
    {
        public static DataGridCell GetCell(DataGridCellInfo dgCellInfo)
        {
            if (!(dgCellInfo.IsValid))
            {
                return null;
            }

            FrameworkElement dgCellContent = dgCellInfo.Column.GetCellContent(dgCellInfo.Item);
            if (dgCellContent != null)
            {
                return (DataGridCell)dgCellContent.Parent;
            }
            else
            {
                return null;
            }
        }

        public static object GetRowItem(DataGridCell dgCell)
        {
            PropertyInfo dgCell_RowDataItemProp = typeof(DataGridCell).GetProperty("RowDataItem", BindingFlags.Instance | BindingFlags.NonPublic);

            return dgCell_RowDataItemProp.GetValue(dgCell, null);
        }

        public static DataGrid GetDataGridFromChild(DependencyObject dataGridPart)
        {
            if (VisualTreeHelper.GetParent(dataGridPart) == null)
            {
                throw new NullReferenceException("Cell is null.");
            }
            if (VisualTreeHelper.GetParent(dataGridPart) is DataGrid)
            {
                return (DataGrid)VisualTreeHelper.GetParent(dataGridPart);
            }
            else
            {
                return GetDataGridFromChild(dataGridPart);
            }
        }
    }
}
